#import "Connector.h"

// ref http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/Streams/Articles/NetworkStreams.html

@implementation Connector

-(void)init:(NSString *)ip port:(int) port{
	[NSStream getStreamsToHost:[NSHost hostWithAddress:ip] 
						  port:port 
			       inputStream:&inStream 
				  outputStream:&outStream];
	[inStream retain];
	[outStream retain];
	[inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[inStream open];
	[outStream open];
	// todo:
	// we should add judgement code to tell whether we are connected
}

-(void)sendStr:(NSString *) s{
	s=[s stringByAppendingString:@"\n"];
	NSData *d=[s dataUsingEncoding:NSUTF8StringEncoding];
	[outStream write: (uint8_t * )[d bytes] maxLength:[d length]];
}

/*
-(void)sendData:(NSData *) d{
	NSLog(@"Connector: sendData");
	NSLog(@"%@\n",d);
	[outStream write: (uint8_t * )[d bytes] maxLength:[d length]];
}
*/

-(NSString *)recvPacket{
	int toread=4;
	uint8_t lenbuf[4];
	while(toread>0){
		int n=[inStream read:buffer maxLength:toread];
		if(n>0){
			memcpy(lenbuf+(4-toread),buffer,n);
			toread-=n;
		}
	}
	unsigned int len=lenbuf[0]+(lenbuf[1]<<8)+(lenbuf[2]<<16)+(lenbuf[3]<<24);
	NSLog(@" recv packet, size is %d",len);
	NSString *ret=[NSString new];
	while(len>0){
		int n=0;
		if(len>RECV_BUF_SIZE){
			n=[inStream read:buffer maxLength:RECV_BUF_SIZE];
		}else{
			n=[inStream read:buffer maxLength:len];
		}
		buffer[n]='\0';
		if(n>0){
			len-=n;
			ret=[ret stringByAppendingString:[[NSString alloc]initWithUTF8String:(char *)buffer]];
		}
	}
	if([ret length]>0)return ret;
	return nil;
}

-(void)finish{
	[inStream close];
	[outStream close];
	[inStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[outStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[inStream setDelegate:nil];
	[outStream setDelegate:nil];
	[inStream release];
	[outStream release];
	inStream = nil;
	outStream = nil;
}

-(void)dealloc{
	[super dealloc];
}

@end
